package com.jeethink.web.controller.system;

import java.util.Date;
import java.util.List;
import java.util.Map;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.StrUtil;
import com.jeethink.system.domain.LabDto;
import com.jeethink.system.domain.SysUserDto;
import com.jeethink.system.domain.SysUserVo;
import com.jeethink.system.service.ISysDictDataService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.jeethink.common.annotation.Log;
import com.jeethink.common.base.AjaxResult;
import com.jeethink.common.enums.BusinessType;
import com.jeethink.common.page.TableDataInfo;
import com.jeethink.common.utils.StringUtils;
import com.jeethink.common.utils.poi.ExcelUtil;
import com.jeethink.framework.shiro.service.SysPasswordService;
import com.jeethink.framework.util.ShiroUtils;
import com.jeethink.framework.web.base.BaseController;
import com.jeethink.system.domain.SysUser;
import com.jeethink.system.service.ISysPostService;
import com.jeethink.system.service.ISysRoleService;
import com.jeethink.system.service.ISysUserService;

import javax.annotation.Resource;

/**
 * 用户信息
 *
 * @author jeethink  官方网站：www.jeethink.vip
 */
@Controller
@RequestMapping("/system/user")
public class SysUserController extends BaseController {
    private String prefix = "system/user";

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private ISysPostService postService;

    @Autowired
    private SysPasswordService passwordService;

    @Resource
    private ISysDictDataService sysDictDataService;
    @RequiresPermissions("system:user:view")
    @GetMapping()
    public String user() {
        int userno = ShiroUtils.getUserId().intValue();
        String roleNo = userService.selectUserRoleGroup2(new Long((long) userno));
        if ("5".equals(roleNo) || "6".equals(roleNo) || "7".equals(roleNo) || "8".equals(roleNo) || "11".equals(roleNo)) {
            return prefix + "/user1";
        } else {
            return prefix + "/user";
        }
    }

    @RequiresPermissions("system:user:detail")
    @GetMapping("/detail/{userId}")
    public String detail(@PathVariable("userId") Long userId, ModelMap mmap)
    {
        SysUser sysUser = userService.selectUserById(userId);
        SysUserVo vo = new SysUserVo();
        vo.setUserId(sysUser.getUserId());
        vo.setDeptId(sysUser.getDeptId());
        vo.setParentId(sysUser.getParentId());
        vo.setLoginName(sysUser.getLoginName());
        vo.setUserName(sysUser.getUserName());
        vo.setEmail(sysUser.getEmail());
        vo.setPhonenumber(sysUser.getPhonenumber());
        if (sysUser.getBirthday() !=null){
            vo.setAge(DateUtil.ageOfNow(sysUser.getBirthday()));
        }
        String sex = sysUser.getSex();
        if (CharSequenceUtil.isNotBlank(sex)){
            if (CharSequenceUtil.equalsIgnoreCase(sex, "0")){
                vo.setSex("男");
            }else if (CharSequenceUtil.equalsIgnoreCase(sex, "1")){
                vo.setSex("女");
            }else {
                vo.setSex("未知");
            }
        }
        vo.setLoginIp(sysUser.getLoginIp());
        vo.setLoginDate(DateUtil.format(sysUser.getLoginDate(), DatePattern.NORM_DATETIME_PATTERN));
        vo.setEthnic(sysUser.getEthnic());
        vo.setNativePlace(sysUser.getNativePlace());
        vo.setBirthday(DateUtil.format(sysUser.getBirthday(), DatePattern.NORM_DATETIME_PATTERN));
        vo.setEducation(sysUser.getEducation());
        vo.setGraduatedSchool(sysUser.getGraduatedSchool());
        vo.setJoinJobTime(DateUtil.format(sysUser.getJoinJobTime(), DatePattern.NORM_DATETIME_PATTERN));
        vo.setApplicationTime(DateUtil.format(sysUser.getApplicationTime(), DatePattern.NORM_DATETIME_PATTERN));
        vo.setPartyTime(DateUtil.format(sysUser.getPartyTime(), DatePattern.NORM_DATETIME_PATTERN));
        vo.setPositiveTime(DateUtil.format(sysUser.getPositiveTime(), DatePattern.NORM_DATETIME_PATTERN));
        vo.setPartyPosition(sysUser.getPartyPosition());
        vo.setAdministrativeDuties(sysUser.getAdministrativeDuties());
        String technicalTitles = sysUser.getTechnicalTitles();
        if (StrUtil.isNotBlank(technicalTitles)){
            vo.setTechnicalTitles(sysDictDataService.selectDictLabel("echnical_titles", technicalTitles));
        }

        String personnelStatus = sysUser.getPersonnelStatus();
        if (StrUtil.isNotBlank(personnelStatus)){
            vo.setPersonnelStatus(sysDictDataService.selectDictLabel("personnel_status", personnelStatus));
        }
        
        
        String status = sysUser.getStatus();
        if (CharSequenceUtil.isNotBlank(status)){
            if (CharSequenceUtil.equalsIgnoreCase(status, "0")){
                vo.setStatus("正常");
            }else {
                vo.setStatus("停用");
            }
        }


        if (sysUser.getBirthday() !=null){
            sysUser.setAge(DateUtil.ageOfNow(sysUser.getBirthday()));
        }
        vo.setRoles(sysUser.getRoles());
        vo.setDept(sysUser.getDept());
        mmap.put("user", vo);
        mmap.put("roles", roleService.selectRolesByUserId(userId));
        mmap.put("posts", postService.selectPostsByUserId(userId));
        return prefix + "/detail";
    }

    @RequiresPermissions("system:user:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(SysUser user) {
        int userno = ShiroUtils.getUserId().intValue();
        String roleNo = userService.selectUserRoleGroup2(new Long((long) userno));
        if ("5".equals(roleNo) || "6".equals(roleNo) || "7".equals(roleNo) || "8".equals(roleNo) || "11".equals(roleNo)) {
            Long deptId = ShiroUtils.getSysUser().getDeptId();
            user.setDeptId(deptId);
        }
        startPage();
        List<SysUser> list = userService.selectUserList(user);
        return getDataTable(list);
    }

    @PostMapping("/selectSysUserCount")
    @ResponseBody
    public Map<String,String> selectSysUserCount(){
        return userService.selectSysUserCount();
    }

    @PostMapping("/selectSysUserCountWithGinseng")
    @ResponseBody
    public  List<LabDto> selectSysUserCountWithGinseng(SysUser user){
        int userno = ShiroUtils.getUserId().intValue();
        String roleNo = userService.selectUserRoleGroup2(new Long((long) userno));
        if ("5".equals(roleNo) || "6".equals(roleNo) || "7".equals(roleNo) || "8".equals(roleNo) || "11".equals(roleNo)) {
            Long deptId = ShiroUtils.getSysUser().getDeptId();
            user.setDeptId(deptId);
        }
        return userService.selectSysUserCountWithGinseng(user);
    }
    @PostMapping("/selectSysUserageCount")
    @ResponseBody
    public  List<Integer> selectSysUserageCount(SysUser user){
        int userno = ShiroUtils.getUserId().intValue();
        String roleNo = userService.selectUserRoleGroup2(new Long((long) userno));
        if ("5".equals(roleNo) || "6".equals(roleNo) || "7".equals(roleNo) || "8".equals(roleNo) || "11".equals(roleNo)) {
            Long deptId = ShiroUtils.getSysUser().getDeptId();
            user.setDeptId(deptId);
        }
        return userService.selectSysUserageCount(user);
    }

    @PostMapping("/selectSysUserCountList")
    @ResponseBody
    public List<SysUserDto> selectSysUserCountList(){
        return userService.selectSysUserCountList();
    }

    //正式党员
    @PostMapping("/officialPartyMember")
    @ResponseBody
    public List<SysUser> officialPartyMemberList(){
        SysUser user = new SysUser();
        user.setPersonnelStatus("1");
        return userService.selectUserList(user);
    }

    //发展对象
    @PostMapping("/objectOfDevelopment")
    @ResponseBody
    public List<SysUser> objectOfDevelopmentList(){
        SysUser user = new SysUser();
        user.setPersonnelStatus("2");
        return userService.selectUserList(user);
    }

    //递交申请书
    @PostMapping("/submitApplication")
    @ResponseBody
    public List<SysUser> submitApplicationList(){
        SysUser user = new SysUser();
        user.setPersonnelStatus("3");
        return userService.selectUserList(user);
    }

    //确定为积极分⼦
    @PostMapping("/identifiedAsAnActivist")
    @ResponseBody
    public List<SysUser> identifiedAsAnActivistList(){
        SysUser user = new SysUser();
        user.setPersonnelStatus("4");
        return userService.selectUserList(user);
    }

    /**
     * 查询品质保障部的老师
     *
     * @param user
     * @return
     */
    @RequiresPermissions("system:user:list")
    @PostMapping("/list1")
    @ResponseBody
    public TableDataInfo list1(SysUser user) {
        startPage();
        List<Map<String, Object>> list = userService.selectUserListByRole(user);
        return getDataTable(list);
    }

    @Log(title = "用户管理", businessType = BusinessType.EXPORT)
    @RequiresPermissions("system:user:export")
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(SysUser user) {
        List<SysUser> list = userService.selectUserList(user);
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        return util.exportExcel(list, "用户数据");
    }

    @Log(title = "用户管理", businessType = BusinessType.IMPORT)
    @RequiresPermissions("system:user:import")
    @PostMapping("/importData")
    @ResponseBody
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        List<SysUser> userList = util.importExcel(file.getInputStream());
        String operName = getSysUser().getLoginName();
        String message = userService.importUser(userList, updateSupport, operName);
        return AjaxResult.success(message);
    }

    @RequiresPermissions("system:user:view")
    @GetMapping("/importTemplate")
    @ResponseBody
    public AjaxResult importTemplate() {
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        return util.importTemplateExcel("用户数据");
    }

    /**
     * 新增用户
     */
    @GetMapping("/add")
    public String add(ModelMap mmap) {
        mmap.put("roles", roleService.selectRoleAll());
        mmap.put("posts", postService.selectPostAll());
        return prefix + "/add";
    }

    /**
     * 新增保存用户
     */
    @RequiresPermissions("system:user:add")
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @Transactional(rollbackFor = Exception.class)
    @ResponseBody
    public AjaxResult addSave(SysUser user) {
        if (StringUtils.isNotNull(user.getUserId()) && SysUser.isAdmin(user.getUserId())) {
            return error("不允许修改超级管理员用户");
        }
        user.setSalt(ShiroUtils.randomSalt());
        user.setPassword(passwordService.encryptPassword(user.getLoginName(), user.getPassword(), user.getSalt()));
        user.setCreateBy(ShiroUtils.getLoginName());
        //给用户添加默认图片
        //user.setAvatar("http://whhp.oss-cn-hangzhou.aliyuncs.com/image/head/admin.jpg");
        //将用户信息添加到缓存
//        stringRedisTemplate.opsForValue().set("testuser", user.toString());
//        System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>打印缓存>>>>>>");
//        System.out.println(stringRedisTemplate.opsForValue().get("testuser"));
//        System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>缓存打印完成>>>>>>");
        return toAjax(userService.insertUser(user));
    }

    /**
     * 修改用户
     */
    @GetMapping("/edit/{userId}")
    public String edit(@PathVariable("userId") Long userId, ModelMap mmap) {
        mmap.put("user", userService.selectUserById(userId));
        mmap.put("roles", roleService.selectRolesByUserId(userId));
        mmap.put("posts", postService.selectPostsByUserId(userId));
        return prefix + "/edit";
    }

    /**
     * 修改保存用户
     */
    @RequiresPermissions("system:user:edit")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @Transactional(rollbackFor = Exception.class)
    @ResponseBody
    public AjaxResult editSave(SysUser user) {
        if (StringUtils.isNotNull(user.getUserId()) && SysUser.isAdmin(user.getUserId())) {
            return error("不允许修改超级管理员用户");
        }
        user.setUpdateBy(ShiroUtils.getLoginName());
        return toAjax(userService.updateUser(user));
    }

    @RequiresPermissions("system:user:resetPwd")
    @Log(title = "重置密码", businessType = BusinessType.UPDATE)
    @GetMapping("/resetPwd/{userId}")
    public String resetPwd(@PathVariable("userId") Long userId, ModelMap mmap) {
        mmap.put("user", userService.selectUserById(userId));
        return prefix + "/resetPwd";
    }

    @RequiresPermissions("system:user:resetPwd")
    @Log(title = "重置密码", businessType = BusinessType.UPDATE)
    @PostMapping("/resetPwd")
    @ResponseBody
    public AjaxResult resetPwdSave(SysUser user) {
        user.setSalt(ShiroUtils.randomSalt());
        user.setPassword(passwordService.encryptPassword(user.getLoginName(), user.getPassword(), user.getSalt()));
        return toAjax(userService.resetUserPwd(user));
    }

    @RequiresPermissions("system:user:remove")
    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        try {
            return toAjax(userService.deleteUserByIds(ids));
        } catch (Exception e) {
            return error(e.getMessage());
        }
    }

    /**
     * 校验用户名
     */
    @PostMapping("/checkLoginNameUnique")
    @ResponseBody
    public String checkLoginNameUnique(SysUser user) {
        return userService.checkLoginNameUnique(user.getLoginName());
    }

    /**
     * 校验手机号码
     */
    @PostMapping("/checkPhoneUnique")
    @ResponseBody
    public String checkPhoneUnique(SysUser user) {
        return userService.checkPhoneUnique(user);
    }

    /**
     * 校验email邮箱
     */
    @PostMapping("/checkEmailUnique")
    @ResponseBody
    public String checkEmailUnique(SysUser user) {
        return userService.checkEmailUnique(user);
    }

    /**
     * 用户状态修改
     */
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @RequiresPermissions("system:user:edit")
    @PostMapping("/changeStatus")
    @ResponseBody
    public AjaxResult changeStatus(SysUser user) {
        return toAjax(userService.changeStatus(user));
    }

    /**
     * 选择list
     */
    @GetMapping("/selectList")
    public String selectList(SysUser user, ModelMap mmap) {
        user.setStatus("0");
        int userno = ShiroUtils.getUserId().intValue();
        String roleNo = userService.selectUserRoleGroup2(new Long((long) userno));
        if ("5".equals(roleNo) || "6".equals(roleNo) || "7".equals(roleNo) || "8".equals(roleNo) || "11".equals(roleNo)) {
            Long deptId = ShiroUtils.getSysUser().getDeptId();
            user.setDeptId(deptId);
        }
        List<SysUser> list = userService.selectUserList(user);
        mmap.put("user", list);
        return prefix + "/list";
    }

    /**
     * 选择list
     */
    @GetMapping("/selectList1")
    public String selectList1(SysUser user, ModelMap mmap) {
        user.setStatus("0");
        List<Map<String, Object>> list = userService.selectUserListByRole(user);
        mmap.put("user", list);
        return prefix + "/list1";
    }


    /**
     * 加载人员列表树
     *
     * @author: wsj
     * @createTime: 2022/9/4 23:09
     */
    @GetMapping("/treeData")
    @ResponseBody
    public List<Map<String, Object>> treeData() {
        List<Map<String, Object>> tree = userService.selectUserTree();
        return tree;
    }
}